package cn.nju.zyy.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import cn.nju.zyy.dao.UserDAO;
import cn.nju.zyy.domain.Community;
import cn.nju.zyy.domain.Country;
import cn.nju.zyy.domain.User;
import cn.nju.zyy.service.UserService;
import cn.nju.zyy.validator.UserValidator;

@Controller
@SessionAttributes("user")
public class UserController {

	private UserDAO userDAO;
	private UserService userService;
//	private UserValidator userValidator;

	@Autowired
	public UserController(UserDAO userDAO, UserService userService, UserValidator userValidator) {
		this.userDAO = userDAO;
		this.userService = userService;
//		this.userValidator = userValidator;
	}

	/**
	 * The @ModelAttribute annotation used at the method level is used to
	 * indicate that the method contain reference data used by the model, so it
	 * should be called before the form is loaded.
	 * 
	 * @return
	 */
	@ModelAttribute("countryList")
	public List<Country> populateCountryList() {
		return userService.getAllCountries();
	}

	@ModelAttribute("communityList")
	public List<Community> populateCommunityList() {
		return userService.getAllCommunities();
	}

//	public String onSubmit(@ModelAttribute("user") User user, BindingResult result) {
//		userValidator.validate(user, result);
//		if (result.hasErrors()) {
//			return "userForm";
//		} else {
//			userService.add(user);
//			return "redirect:userSuccess.html";
//		}
//	}
	
	@RequestMapping("/user/add.html")
	public ModelAndView add(HttpServletRequest request, 
			HttpServletResponse response, User user) throws Exception {
		userDAO.saveUser(user);
		return new ModelAndView("redirect:list.html");
	}
	
	@RequestMapping("/user/list.html")
	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelMap model = new ModelMap();
		model.addAttribute("userList", userDAO.listUser());
		model.addAttribute("user", new User());
		return new ModelAndView("userForm", model);
	}

}
